//获取应用实例
const app = getApp();
var util = require('../../utils/util.js');
var QQMapWX = require('../../dist/js/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
  key: 'HLFBZ-EGZK6-MVQS6-ESMKT-T2G37-GIB2U' // 必填
});
var userArea, _this;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    searchArea: null,      // 地址
    addressList: [],
    buttonClicked: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    _this = this;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },
  searchArea: function(e){
    var text = e.detail.value
    qqmapsdk.getSuggestion({
      keyword: text,
      region_fix: 0,
      region: '全国',
      success: function (res) {
        _this.setData({
          addressList : res.data
        })
        console.log(res);
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
  searchAndBack:function(e){
    var index = e.currentTarget.dataset.index;
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];  //上一个页面
    var userArea = prevPage.data.submitArea;
    //userArea.longitude = _this.data.addressList[index].location.lng
    //userArea.latitude = _this.data.addressList[index].location.lat
    var res = _this.data.addressList[index]
    _this.judgeAddress(res, userArea, index);
  },
  goBack:function(){
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateBack({
        delta: 1
      })
    }
  },
  judgeAddress: function (res, userArea, index) {
    // 之前的地址 —— 区
    var area = userArea.district;
    var adcode = userArea.adcode;
    var detailAdcode = res.adcode;
    if (adcode != detailAdcode) {
      // 超过区域，重新选择地区
      var aa = '超出' + userArea.district + '请重新选择';
      util.alertMsg('提示', aa, function () {
        console.log('用户点击确定')
        return;
      }, function () {
        console.log('用户点击取消')
        return;
      });
      return;
    }else{
      var pages = getCurrentPages();
      var currPage = pages[pages.length - 1];   //当前页面
      var prevPage = pages[pages.length - 2];  //上一个页面
      var userArea = prevPage.data.userArea;
      userArea.latitude = res.location.lat;
      userArea.longitude = res.location.lng;
      prevPage.setData({
        userArea: userArea
      })
      res.formatted_addresses = {
        recommend: res.address
      }
      prevPage.judgeAddress(res);
      if (!_this.data.buttonClicked) {
        util.buttonClicked(_this);
        wx.navigateBack({
          delta: 1
        })
      }
    }
  }
})

